//
//  SignInViewController.m
//  PokerHandUp
//
//  Created by psvn047 on 6/8/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SignInViewController.h"
#import "SignUpViewController.h"
#import "AppDelegate.h"
#import "AccountService.h"
#import "ValidateUtils.h"

@implementation SignInViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
    [tfEmail release];
    [tfPassword release];
}
#pragma mark - ServiceCallbackDelegate
- (void)successedCallback:(NSString*) serviceId reponseData:(NSObject*) data
{
    NSDictionary* json = (NSDictionary*) data;
    if ([serviceId isEqualToString:@"SignIn"]) {
        if(json != NULL)
        {
            if(![BasicHttpService getSession])
            {
                NSDictionary* json = (NSDictionary*) data;
                Session* session = [[Session alloc] init];
                NSString * accountId = [json objectForKey:@"account_id"];
                NSString * appId = [json objectForKey:@"app_id"];
                NSString * authenToken = [json objectForKey:@"session_id"];
                NSString * expiration_time = [json objectForKey:@"expiration_time"];
                NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
                [dateFormatter setDateFormat:@"yyyy/mm/dd hh:mm:ss a"];
                NSDate * date_expiration = [dateFormatter dateFromString:expiration_time];
                [session initSesssion:accountId appId:appId authToken:authenToken expirationTime:date_expiration];
                [BasicHttpService setSession:session];
            }
            
             [[AppDelegate sharedController] showMainScreen];
        }
        else
        {
            NSLog(@"Empty data");
            [self showAlert:@"Alert" message: @"Reponse data is empty"];
        }
        
    }
}
- (void)failedCallback:(NSString*) serviceId reponseData:(NSObject*) data
{
    NSLog(@"failedCallback");
    NSDictionary* json = (NSDictionary*) data;
    [self showAlert:@"Alert" message: [json objectForKey:@"message"]];
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    tfPassword.secureTextEntry = YES;
    
    tfPassword.text = NSLocalizedString(@"signin.text.password", @"");
    tfEmail.text = NSLocalizedString(@"signin.text.email", @"");
}
- (IBAction)signInHandler:(id)sender
{
    BOOL validate = true;
    if(![ValidateUtils validateEmail:tfEmail.text] )
    {
        validate = false;
    }
    if(validate)
    {
        // Test service
        AccountService* service = [[AccountService alloc] init];
        service.serviceCallbackDelegate = self;
        [service signIn:@"SignIn" emailAddress:tfEmail.text password:tfPassword.text];
    }
    else
    {
        [self showAlert: @"Alert" message: @"Please input data"];
    }

}
- (IBAction)cancelHandler:(id)sender
{
     [[AppDelegate sharedController] showWelcomeScreen];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// Edit funtion

-(void)textFieldDidEndEditing:(UITextField *)textField 
{
    NSString* trimStr = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if([trimStr compare: @""] == NSOrderedSame)
    {
        if(textField == tfEmail)
        {
            textField.text = NSLocalizedString(@"signin.text.email", @"");
        }
        else if(textField == tfPassword)
        {
            textField.text = NSLocalizedString(@"signin.text.password", @"");
        }
    }
    [tfActive resignFirstResponder];
    tfActive = NULL;
    
}
          
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return YES;
}
     
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
        tfActive = textField;
    if(tfActive == tfEmail)
    {
        if([tfActive.text compare:NSLocalizedString(@"signin.text.email", @"")] == NSOrderedSame)
        {
            tfActive.text = @"";
        }
    }
    else if(tfActive == tfPassword)
    {
        if([tfActive.text compare:NSLocalizedString(@"signin.text.password", @"")] == NSOrderedSame)
        {
            tfActive.text = @"";
        }
    }
}
     
     
-(void) showAlert:(NSString*) title message: (NSString*)message
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}
@end
